import flarum from "../flarum";

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const setStorage = (key, data) => {
  return wx.setStorageSync(key, data)
}

const getStorage = (key) => {
  return wx.getStorageSync(key)
}

const getFlarum = () => {
  return getStorage(flarum.cache.flarum)
}

const getIdentity = () => {
  return getStorage(flarum.cache.identity)
}

const checkLoginStatus = () => {
  const identity = getIdentity() ?? {}
  if (identity.length <= 0) {
    return {uid: 0, isLogin: false}
  }
  const uid  = identity.uid ?? 0
  const isLogin = !!uid

  return {uid: uid, isLogin: isLogin}
}

const formatOptions = data => {
  const links = data.links ?? {}
  let hasMore

  if (links.length <= 0) {
    hasMore = false
  } else {
    const next = links.next ?? ""
    hasMore = next !== "";
  }

  return {
    hasMore: hasMore,
    links: links
  }
}

module.exports = {
  formatTime,
  checkLoginStatus,
  formatOptions,
  getStorage,
  setStorage,
  getIdentity,
  getFlarum
}
